import * as qiniu from 'qiniu-js';
import { qiniuSpace } from '../../my-config';
import requests from '@/config/api';
/**
 * 上传图片至七牛
 * @author 张振东
 * @param {file} file 文件对象
 * @return {promise} resolve：上传成功后的该图片地址。reject：失败信息，具体见七牛jssdk文档
 */
// export default function(file) {
// 	return new Promise((resolve, reject) => {
// 		// 具体请根据接口返回数据格式进行修改
// 		_request({ url: 'common/getQiniuToken' }).then(({ ret: token }) => {
// 			var key = 'image/' + new Date().getTime() + file.name;
// 			var obs = qiniu.upload(file, key, token);
// 			var cb = {
// 				complete: ({ key }) => resolve(qiniuSpace + key),
// 				error: reject,
// 			};
// 			obs.subscribe(cb);
// 		});
// 	});
// }
export default (file, finished, progress) => {
	requests.api_global_getQiniuToken({})
		.then((res) => {
			console.log(res);
			let token = res.data || '';
			let file_suffix = file.name.substr(file.name.lastIndexOf('.'));
			let key = `ZHYL_H5${new Date().getTime()}${file_suffix}`;
			let observable = qiniu.upload(file, key, token);
			let cb = {
				complete: (res) =>
					finished({
						file_url: qiniuSpace + res.key,
						file_name: res.key,
						file_size: file.size / 1000,
						file_type: file.type,
					}),
				error: (err) => finished(err),
			};

			if (typeof progress == 'function') cb.next = (object) => progress(object.total.percent);

			observable.subscribe(cb);
		})
		.catch(() => {
			finished(false);
		});
};
